<?php
/***
 * 新闻模块
 */

namespace App\Http\Controllers\Api\V1;

use App\Http\Resources\NewsResource;
use App\Models\Category;
use App\Models\Config;
use App\Models\New_Category;
use App\Models\News;
use Illuminate\Http\Request;

class NewController extends ApiController
{
    //新闻列表
    public function index(Request $request, News $news)
    {
        $query = $news->query();
        if ($categoryId = $request->category_id) {
            $query->where('category_id', $categoryId);
        }
        $newss = $query->with('user')->where('status', 2)->withOrder($request->order)->paginate();
        return $this->success('成功', NewsResource::collection($newss));
    }

    //获取单个新闻数据
    public function show($newId, News $news)
    {
        $newinfo = $news->with('user')->where('id', $newId)->first();
        if ($newinfo) {
            $newinfo->updateViewCount();
        }
        return $this->success('成功', NewsResource::make($newinfo));
    }

    public function add(Request $request, News $news)
    {
        $news->uid = $this->getUserId();
        $title = $request->input('title');
        $body = $request->input('body');
        $config = Config::getConfig('article');
        if (empty($title)) {
            return $this->error('标题不能为空');
        }
        if (empty($title)) {
            return $this->error('内容不能为空');
        }
        $news->title = $title;
        $news->body = $body;
        if (!empty($request->images) && count($request->images) && is_array($request->images)) {
            $news->imgs = json_encode($request->images);
        }
        if (!empty($request->videos) && count($request->videos) && is_array($request->videos)) {
            $news->videos = json_encode($request->videos);
        }
        $news->category_id = $request->category_id;
        if ($config['article_open_check'] == '1') {
            $news->status = 1;
        } else {
            $news->status = 2;
        }
        if ($news->save()) {
            return $this->success('发布成功', NewsResource::make($news));
        } else {
            return $this->error('发布失败');
        }

    }

    public function getNewCategory()
    {
        $list = New_Category::select('id', 'name', 'description', 'sort')->orderBy('sort', 'asc')->get();
        return $this->success('成功', $list);
    }

}
